<?php
if (!defined("APP_PATH")) {
    define('APP_PATH',__DIR__.'/../application/');
    // 加载框架引导文件
    require  __DIR__.'/../thinkphp/start.php';
}

use think\Db;
use think\Exception;
use think\Log;
use fast\Http;

echo "<pre>";
set_time_limit(0);


//每8分钟触发一次
while (true) {
    get_order_result();
    sleep(60);
}


function get_order_result()
{
    $debug = config("app_debug");
    if (php_sapi_name() != 'cli' && !$debug) {
        // echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }

    echo '开始执行的时间：'.date('Y-m-d H:i:s')."\r\n";

    $redis = rds();
    $bkey = 'get_order_result';
    if($debug)
        delkey($redis,$bkey);
    $op = $redis->set($bkey,1,['NX','EX'=>450]);
    if(!$op){
        echo '请勿频繁操作：'.date('Y-m-d H:i:s')."\r\n";
        goto END1;
    }

    $prefix = config('database.prefix');
    $time = time();
//    $d = date('Ymd');
    $orders = \db('tron_order')->alias('o')
        ->join('user_detail ud', 'ud.uid = o.uid')
        ->where('o.status',0)
        ->column('o.id,o.uid,o.type,o.amt,o.txid,ud.tjstr','o.id');
    // var_dump($orders);die;
    if(!empty($orders)){
        $tz_frozen_users = [];
        $tz_frozen = [];//会员投资额度释放冻结资产
        $investments = [];//会员投资额度
        $withdrawals = [];//提现失败-返还会员收益
        $add_inv = 0;//矿池余额增加(投资)
        $add_jazkpot = 0;//奖池增加
        $share_award = 0;//分享矿池
        $to_status = '';
        $oids = '';
        $init_untxday = '';
        $url = config('transaction')['fullNode_url'].'/wallet/gettransactionbyid';
        $pvArrays = []; //小区业绩
        foreach($orders as $order){
            if(empty($order['txid'])) continue;
            $result = Http::post($url,json_encode(['value'=>$order['txid']]));
//            var_dump($result);
            if($result == '') continue;
            $result = json_decode($result,1);
            if(!empty($result['ret'][0]['contractRet']) && $result['ret'][0]['contractRet'] == 'SUCCESS') {//交易结果为成功

                //如果金额不一致则返回
                if($result['raw_data']['contract'][0]['parameter']['value']['amount'] / 1000000 != $order['amt']) {
                    Log::error("order exception：amt". $order['id']);
                    continue;
                }

                $address = $result['raw_data']['contract'][0]['parameter']['value']['to_address'];

                if($address != "4109beb812564ad2c574866a286e77945853eca1fd") {
                    Log::error("order exception：address". $order['id']);
                    continue;
                }

                $to_status .= " when id={$order['id']} then 1 ";
                $oids .= ",{$order['id']}";
                if($order['type'] == 0){//投资
                    $add_inv += $order['amt'];

                    $tz_frozen_users[$order['uid']] = isset($tz_frozen_users[$order['uid']]) ? $tz_frozen_users[$order['uid']]+1 : 1;

                    if(empty($investments[$order['uid']])){
                        $investments[$order['uid']] = $order['amt'];
                        $tz_frozen[$order['uid']] = $order['amt'];
                    }else{
                        $investments[$order['uid']] += $order['amt'];
                        $tz_frozen[$order['uid']] += $order['amt'];
                    }
                    $new_tjstr = $order['uid'].",".$order['tjstr'];
                    $tjstr_arr = explode(',', $new_tjstr);
                    foreach ($tjstr_arr as $value) {
                        if(empty($pvArrays[$value])){
                            $pvArrays[$value] = $order['amt'];
                        }else{
                            $pvArrays[$value] += $order['amt'];
                        }
                    }


                }else{//提现
                    //0.005进入重新矿池以及奖池
                    $add_jazkpot += $order['amt']*0.05;
                    //0.01进入分享矿池
                    $share_award += $order['amt']*0.1;
                    //提现成功清零不提现天数
                    $init_untxday .= ",{$order['uid']}";
                }
            }elseif(!empty($result['Error']) || (!empty($result['ret'][0]['contractRet']) && ($result['ret'][0]['contractRet'] == 'REVERT' ||  $result['ret'][0]['contractRet'] == 'OUT_OF_ENERGY'))){//交易结果为失败
                $to_status .= " when id={$order['id']} then 2 ";
                $oids .= ",{$order['id']}";
                if($order['type'] == 1){//提现失败
                    $add_inv += $order['amt'];//返还矿池余额
                    if(empty($withdrawals[$order['uid']])){
                        $withdrawals[$order['uid']] = $order['amt'];
                    }else{
                        $withdrawals[$order['uid']] += $order['amt'];
                    }
                }
            }
        }
        unset($orders);
        if($to_status){
            $oids = trim($oids,',');
            $to_status = "UPDATE {$prefix}tron_order SET status=(case {$to_status} else status end),updatetime=(case when id in ({$oids}) then '{$time}' else updatetime end)";
        }

        $u_credit1 = '';
        $tz_frozen_bi = '';
        $tz_frozen_dec = '';
        //会员投资额度增长
        if($investments){
            foreach($investments as $uid=>$investment){
                if($investment > 0) {
                    $u_credit1 .= " when id={$uid} then credit1+{$investment} ";
                }
            }
        }
        //投资释放冻结资产
        if (config("site.tz_frozen_bi") && $tz_frozen_users) {
            $uids = implode(',',array_keys($tz_frozen_users));
            $frozen_sum_users = \db('user')->whereIn('id',$uids)->column('id,frozen_sum','id');
            foreach($tz_frozen_users as $uid=>$tz_num){
                if (empty($frozen_sum_users[$uid])) continue;
                $free_num = 0;
                if ($tz_num > 1) { //投资次数
                    for ($i = 0; $i < $tz_num; $i++) {
                        $free_num += $frozen_sum_users[$uid] * config("site.tz_frozen_bi") / 100;
                        $frozen_sum_users[$uid] -= $free_num;
                    }
                } else {
                    $free_num = $frozen_sum_users[$uid] * config("site.tz_frozen_bi") / 100;
                }
                $tz_frozen_bi .= " when id={$uid} then credit2+{$free_num} ";
                $tz_frozen_dec .= " when id={$uid} then frozen_sum-{$free_num} ";
            }
         }

        $u_credit2 = '';
        //提现失败返还会员收益
        if($withdrawals){
            foreach($withdrawals as $uid=>$withdrawal){
                $u_credit2 .= " when id={$uid} then credit2+{$withdrawal} ";
            }
        }

        $u_pv = '';
        $u_pv_sum = '';
        //小区业绩
        if($pvArrays){
            foreach($pvArrays as $uid=>$pv){
                if($pv > 0) {
                    $u_pv .= " when id={$uid} then pv+{$pv} ";
                    $u_pv_sum .= " when id={$uid} then pv_sum+{$pv} ";
                }
            }
        }

        unset($withdrawals);

        $u_update = '';
        if($u_credit1){
            $u_update = " credit1=(case {$u_credit1} else credit1 end)";
        }
        if ($tz_frozen_bi) {
            $u_update .= ",credit2=(case {$tz_frozen_bi} else credit2 end)";
        }
        if($u_credit2){
            $u_update .= ",credit2=(case {$u_credit2} else credit2 end)";
        }
        if($u_pv){
            $u_update .= ",pv=(case {$u_pv} else pv end)";
        }
        if($u_pv_sum){
            $u_update .= ",pv_sum=(case {$u_pv_sum} else pv_sum end)";
        }
        if ($tz_frozen_dec) {
            $u_update .= ",frozen_sum=(case {$tz_frozen_dec} else frozen_sum end)";
        }
        if($init_untxday){
            $init_untxday = trim($init_untxday,',');
            $u_update .= ",untxday=(case when id in ({$init_untxday}) then 0 else untxday end)";
        }

        db::startTrans();
        try {
            if($to_status) \db()->execute($to_status);
            if($u_update) \db()->execute("UPDATE {$prefix}user SET ".trim($u_update,','));
            if($investments){//增加缓存中的会员投资额度
                foreach($investments as $uid=>$investment){
                    $redis->hIncrByFloat(REDIS_PREFIX.'user_tz','user_'.$uid,$investment);
                }
            }

            //增加矿池余额
            if($add_inv > 0){
                \db('config')->where('name','kc_balance')->setInc('value',$add_inv);
                $redis->del('kc_restart');
                //如果矿池处于重启状态则恢复正常 且还有重启次数 可继续注册投资提现
                //if(\db('config')->where('name','kc_restart_num')->value('value') > 0) $redis->del('kc_restart');
            }
            //增加奖池和重生矿池
            if($add_jazkpot > 0){
                \db('config')->where('name','kc_jackpot')->setInc('value',$add_jazkpot);
                \db('config')->where('name','reborn_kc')->setInc('value',$add_jazkpot);
            }
            //增加分享矿池
            if($share_award > 0){
                \db('config')->where('name','kc_share')->setInc('value',$share_award);
            }
            db::commit();
        }catch (\Exception $e){
            db::rollback();
            Log::error($e->getMessage());
            echo $e->getMessage();
            echo '执行失败：'.date('Y-m-d H:i:s')."\r\n";
        }
        //释放三层冻结资金
        if ($tz_frozen) {
            $fz_release_arr = [];
            $bi_arr = [5, 3, 2]; //三层比例
            $fz_uids = implode(',',array_keys($tz_frozen));
            $fz_users = \db('user_detail')->whereIn('uid',$fz_uids)->column('uid,tjstr,tjdept','uid');
            if ($fz_users) {
                foreach ($fz_users as $fz_k => $fz_value) {
                    $fz_tjstr = explode(',',$fz_value['tjstr']);
                    if (empty($tz_frozen[$fz_k])) continue;
                    for ($i = 0; $i < 3; $i++) {
                        if (empty($fz_tjstr[$i])) continue;
                        $profit = $tz_frozen[$fz_k] * $bi_arr[$i] / 100;
                        $fz_release_arr[$fz_tjstr[$i]] = ($fz_release_arr[$fz_tjstr[$i]] ?? 0) + $profit;
                        echo "=======用户投资{$tz_frozen[$fz_k]}id:{$fz_k},冻结资产释放 ".bcadd($i,1)."代 ID:{$fz_tjstr[$i]}  释放金额：{$profit}========"."\r\n";
                    }
                }
            }

            $fz_release_uids = implode(',',array_keys($fz_release_arr));
            $fz_sum_users = \db('user')->whereIn('id',$fz_release_uids)->column('frozen_sum,credit2','id');

            $update_fz_sql = "";
            $update_credit2_sql = "";

            foreach ($fz_sum_users as $k => $v) {
                if (empty($v['frozen_sum'])) continue;
                if ($v['frozen_sum'] >= $fz_release_arr[$k]) {
                    $t_profit = $fz_release_arr[$k];
                } else {
                    $t_profit = $v['frozen_sum'];
                }
                $update_fz_sql .= " when id = {$k} then frozen_sum - {$t_profit}";
                $update_credit2_sql .= " when id = {$k} then credit2 + {$t_profit}";
            }

            if($update_fz_sql || $update_credit2_sql){
                $update_fz = " frozen_sum = (case {$update_fz_sql} else frozen_sum end)";
                $update_fz .= ",credit2 = (case {$update_credit2_sql} else credit2 end)";
            }
            try {
                \db()->execute("UPDATE {$prefix}user SET ".trim($update_fz,','));
                echo '=======投资释放冻结资产成功'.date('Y-m-d H:i:s')."===========\r\n";
            } catch (\Exception $exception) {
                echo '=======投资释放冻结资产失败：'.$exception->getMessage().date('Y-m-d H:i:s')."===========\r\n";
            }
        }
        //结算动态奖励
        if(0) {
            if($investments && config("site.run_switch")){
                $uids = implode(',',array_keys($investments));
                $users = \db('user_detail')->whereIn('uid',$uids)->column('uid,tjstr,tjdept','uid');
                //动态收益参数
                $dynamic = config("site.runbi_list");
                foreach($dynamic as $dkey=>$dynamic_d){
                    $dynamic[$dkey] = $dynamic_d/100;
                }
                $strids = '';
                foreach($users as $user){
                    $strids .= ",{$user['tjstr']}";
                }
                //所有可能可以获奖的上级
                $str = implode(',',array_unique(explode(',',trim($strids,','))));
                $strUsers = \db('user_detail')
                    ->alias('a')
                    ->join('user_detail b','a.uid=b.tjid')
                    ->join('user ub','b.uid=ub.id')
                    ->where('ub.credit1>0')
                    ->whereIn('a.uid',$str)
                    ->group('a.uid')
                    ->column('a.uid,count(ub.id)','a.uid');
                $addrunArr = [];
                $award_arr = [$dynamic[1], $dynamic[2], $dynamic[3], $dynamic[6], $dynamic[6], $dynamic[6], $dynamic[6], $dynamic[6], $dynamic[6], $dynamic[6]];
                foreach($investments as $uid=>$investment){
                    if(!empty($users[$uid]['tjstr'])){
                        $tjarr = explode(',',$users[$uid]['tjstr']);
                        foreach($tjarr as $dept=>$tjid){
                            //没有投资额度就不能获得收益
                            if(empty($strUsers[$tjid]) || $redis->hGet(REDIS_PREFIX.'user_tz','user_'.$tjid) <= 0) continue;
                            // switch($strUsers[$tjid]){
                            //     case 1:
                            //         if($dept > 0 || empty($dynamic[1])) continue 2;
                            //         $bi = $dynamic[1];
                            //         break;
                            //     case 2:
                            //         if($dept > 1 || empty($dynamic[2])) continue 2;
                            //         $bi = $dynamic[2];
                            //         break;
                            //     case in_array($strUsers[$tjid],[3,4,5]):
                            //         if($dept > 2 || empty($dynamic[3])) continue 2;
                            //         $bi = $dynamic[3];
                            //         break;
                            //     default://直推6人或以上人数
                            //         if(empty($dynamic[6])) continue 2;
                            //         $bi = $dynamic[6];
                            //         break;
                            // }
                            if ($dept > 9) continue; //10层内有奖励
                            if (empty($award_arr[$dept])) continue;
                            switch($strUsers[$tjid]){
                                case 1:
                                    if ($dept > 0) continue 2;
                                    $bi = $award_arr[$dept];
                                    break;
                                case 2:
                                    if ($dept > 1) continue 2;
                                    $bi = $award_arr[$dept];
                                    break;
                                case in_array($strUsers[$tjid],[3,4,5]):
                                    if ($dept > 2) continue 2;
                                    $bi = $award_arr[$dept];
                                    break;
                                default://直推6人或以上人数
                                    if ($dept > 9) continue 2;
                                    $bi = $award_arr[$dept];
                                    break;
                            }
                            $add_sy = $bi * $investment;
                            echo $tjid.'--动态收益:'.$add_sy.">>>";
                            $addrunArr[$tjid] = ($addrunArr[$tjid]??0)+$add_sy;
                            if($dept >= 9) break;
                        }
                    }
                }
                unset($investments);
                foreach($addrunArr as $rUid=>$addRun){
                    $redis->hIncrByFloat(REDIS_PREFIX.'user_sy','user_'.$rUid,$addRun);
                    $redis->hIncrByFloat(REDIS_PREFIX.'dynamic_sy','user_'.$rUid,$addRun);
                }
                unset($addrunArr);
            }
        }

        if($investments && config("site.run_switch")) {
            \app\common\core\BonusSettle::rechargeReward($investments,$redis);
        }
    }else{
        echo '没有需要获取结果的订单：' . date('Y-m-d H:i:s') . "\r\n";
    }

//    END2:
    delkey($redis,$bkey);
    END1:
    echo "\r\n".'结束执行的时间：'.date('Y-m-d H:i:s')."\r\n";
}


